package com.aspire.nm.component.cmppserverDemo;

import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.aspire.nm.component.cmppserver.ClientConfig;
import com.aspire.nm.component.cmppserver.CmppServer;
import com.aspire.nm.component.cmppserverDemo.jsonbean.ClientConfigs;
import com.aspire.nm.component.commonUtil.constants.JsonConfig;
import com.aspire.nm.component.commonUtil.spring.SpringHelper;

public class CmppServerWrapper {
    
    private Logger logger = Logger.getLogger(CmppServerWrapper.class);
    
    
    private CmppServer cmppServer;
    
    
    public CmppServerWrapper() throws UnknownHostException, InstantiationException, IllegalAccessException, ClassNotFoundException{
    	
    	cmppServer = new SpringHelper(new String[]{"classpath*:config/context/demo.xml"}).getBean(CmppServer.class, "cmppServer"); 
    	
    	init();
    }
    
    
    private void init() throws UnknownHostException, InstantiationException, IllegalAccessException, ClassNotFoundException{
    	
    	ClientConfigs clientConfigs = new JsonConfig().getConfigs(ClientConfigs.class,"/config/json/clientconfigs.json");
        
        cmppServer.addBlackIps(clientConfigs.getBlackIps());
        
        for(ClientConfig clientConfig:clientConfigs.getClientConfigs()){
            
            if(clientConfig.getUsername().startsWith("max")){
                for(int i = 1;i<=50;i++){
                    try {
                        ClientConfig c = (ClientConfig) clientConfig.clone();
                        c.setUsername(c.getUsername().replaceAll("#index#", String.valueOf(i)));
                        logger.debug("add Client , " + c.getUsername());
                        cmppServer.addClientConfig(c);
                    } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                logger.debug("add Client , " + clientConfig.getUsername());
                cmppServer.addClientConfig(clientConfig);
            }
        }
    }
    
    
    public void start() throws IOException{
        cmppServer.start();
    }
    
    

    public void stop() throws IOException  {
        cmppServer.stop();
    }

}
